How to Convert HTML to PDF in .NET Core
さまざまな形式からPDFへの変換は、PDF形式の厳格な基準により困難な場合があります。 HTMLおよびCSSスタイリングを扱う場合、多くの場合、変換は1対1の一致をもたらさないことがあります。 しかし、今日のデジタルランドスケープでは、URLやフォーム(HTMLやCSSを含む)を変換する能力が不可欠です。 ここでIronPDFは優れており、開発者がさまざまな形式を数行のコードで高精度でPDFに変換できる直感的な機能を提供します。
IronPDFを使用すると、HTML、DOCX、RTF、Markdown、さらには画像をPDFに簡単に変換でき、ドキュメントの完全性が保たれます。 また、Razor、CSHTML、ASPX、XAMLなどの人気のあるフレームワークの動的なWebページの変換もサポートしており、互換性の問題を排除し、あらゆるPDF変換ニーズに対応する包括的なソリューションとなります。
単純な変換に加えて、IronPDFは強力なカスタマイズオプションを提供します。 ページ番号を含めたカスタムの余白、ヘッダー、フッターを使用してPDF出力を調整し、グレースケール設定を調整してファイルサイズを削減できます。目次、自動ページブレーク、目的のドキュメントサイズに完璧にスケールする内容などの追加機能を組み込むことで、ドキュメントを強化できます。
このチュートリアルでは、これらの機能とその他を探り、コード例を提供し、IronPDFの主要な機能を強調します。 あなたのPDF変換プロセスを変革する準備をし、IronPDFでPDFドキュメントを簡単に変換、カスタマイズ、および最適化できるようにします。
クイックスタート:IronPDFでHTMLをPDFに変換する
.NET CoreでHTMLをPDFに簡単に変換するには、IronPDFを使用して始めてください。 IronPDFの強力なAPIを使用してHTML文字列からピクセル完璧なPDFを1行のコードでレンダリングできます。 このガイドでは、IronPDFをプロジェクトに迅速に統合し、最小限のセットアップでシームレスなPDF生成を可能にする方法を示します。HTML、URL、Razorビューのいずれを変換する場合でも、IronPDFはプロセスを簡素化し、あらゆるレベルの開発者が利用できるようにします。 今日から変換を開始し、準備ができたときに高度な機能を探ってください。
Get started making PDFs with NuGet now:
Install IronPDF with NuGet Package Manager
Copy and run this code snippet.
var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello, PDF!</h1>");Deploy to test on your live environment
目次
- 多用途なPDF変換
- 動的WebページからPDFに
- ウェブアクセシビリティ
- カスタマイズされたPDF変換
- PDFレイアウトの改善
今日あなたのプロジェクトでIronPDFを無料トライアルで使用開始。
多用途なPDF変換
HTML文字列からのPDF
HTML文字列からPDFに変換するには、RenderHtmlAsPdfメソッドを使用してHTML文字列をピクセル完璧なPDFに素早く変換できます。
:path=/static-assets/pdf/content-code-examples/how-to/html-string-to-pdf.cs
using IronPdf;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Create a PDF from a HTML string using C#
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
// Export to a file or Stream
pdf.SaveAs("output.pdf");
Imports IronPdf
' Instantiate Renderer
Private renderer = New ChromePdfRenderer()
' Create a PDF from a HTML string using C#
Private pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
' Export to a file or Stream
pdf.SaveAs("output.pdf")
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
HTMLからのPDF
RenderHtmlAsPdfメソッドを使用して、HTMLファイルを簡単にPDFに変換し、ピクセル完璧なPDFをすぐに保存できます。
:path=/static-assets/pdf/content-code-examples/how-to/html-file-to-pdf.cs
using IronPdf;
using IronPdf.Engines.Chrome;
using IronPdf.Rendering;
var renderer = new ChromePdfRenderer
{
RenderingOptions = new ChromePdfRenderOptions
{
CssMediaType = PdfCssMediaType.Print,
MarginBottom = 0,
MarginLeft = 0,
MarginRight = 0,
MarginTop = 0,
Timeout = 120,
},
};
renderer.RenderingOptions.WaitFor.RenderDelay(50);
// Create a PDF from an existing HTML file using C#
var pdf = renderer.RenderHtmlFileAsPdf("example.html");
// Export to a file or Stream
pdf.SaveAs("output.pdf");
Imports IronPdf
Imports IronPdf.Engines.Chrome
Imports IronPdf.Rendering
Private renderer = New ChromePdfRenderer With {
.RenderingOptions = New ChromePdfRenderOptions With {
.CssMediaType = PdfCssMediaType.Print,
.MarginBottom = 0,
.MarginLeft = 0,
.MarginRight = 0,
.MarginTop = 0,
.Timeout = 120
}
}
renderer.RenderingOptions.WaitFor.RenderDelay(50)
' Create a PDF from an existing HTML file using C#
Dim pdf = renderer.RenderHtmlFileAsPdf("example.html")
' Export to a file or Stream
pdf.SaveAs("output.pdf")
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
URLからのPDF
RenderUrlAsPdfを使用して、URLを数行でPDFに素早く変換します。 URLをパラメータとして入力し、簡単に保存できます。
:path=/static-assets/pdf/content-code-examples/how-to/url-to-pdf.cs
using IronPdf;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Create a PDF from a URL or local file path
var pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");
// Export to a file or Stream
pdf.SaveAs("url.pdf");
Imports IronPdf
' Instantiate Renderer
Private renderer = New ChromePdfRenderer()
' Create a PDF from a URL or local file path
Private pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page")
' Export to a file or Stream
pdf.SaveAs("url.pdf")
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
画像からPDF
PDFとして表示したい画像がありますか? ImageToPdfConverterクラスを使用して迅速に変換し、ImageToPdfメソッドを呼び出します。
:path=/static-assets/pdf/content-code-examples/how-to/image-to-pdf-convert-one-image.cs
using IronPdf;
string imagePath = "meetOurTeam.jpg";
// Convert an image to a PDF
PdfDocument pdf = ImageToPdfConverter.ImageToPdf(imagePath);
// Export the PDF
pdf.SaveAs("imageToPdf.pdf");
Imports IronPdf
Private imagePath As String = "meetOurTeam.jpg"
' Convert an image to a PDF
Private pdf As PdfDocument = ImageToPdfConverter.ImageToPdf(imagePath)
' Export the PDF
pdf.SaveAs("imageToPdf.pdf")
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
PDFから画像
上記の例の逆に、まず入力をPDFに変換し、その後RasterizeToImageFilesメソッドを使用してPDFを画像に変換できます。
:path=/static-assets/pdf/content-code-examples/how-to/rasterize-pdf-to-images-rasterize.cs
using IronPdf;
// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render PDF from web URL
PdfDocument pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");
// Export images from PDF
pdf.RasterizeToImageFiles("wikipage_*.png");
IRON VB CONVERTER ERROR developers@ironsoftware.com
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
DOCXからPDFに変換
履歴書などのDOCXファイルを簡単にPDFに変換する必要がありますか? IronPDFが対応しています。 単にRenderDocxAsPDFを呼び出して変換してください。
:path=/static-assets/pdf/content-code-examples/how-to/docx-to-pdf-from-file.cs
using IronPdf;
// Instantiate Renderer
DocxToPdfRenderer renderer = new DocxToPdfRenderer();
// Render from DOCX file
PdfDocument pdf = renderer.RenderDocxAsPdf("Modern-chronological-resume.docx");
// Save the PDF
pdf.SaveAs("pdfFromDocx.pdf");
Imports IronPdf
' Instantiate Renderer
Private renderer As New DocxToPdfRenderer()
' Render from DOCX file
Private pdf As PdfDocument = renderer.RenderDocxAsPdf("Modern-chronological-resume.docx")
' Save the PDF
pdf.SaveAs("pdfFromDocx.pdf")
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
RTFからPDFに変換
RTFファイルをPDFに変換するには、RTFファイルを入力としてRenderRtfFileAsPdfを呼び出します。
:path=/static-assets/pdf/content-code-examples/how-to/rtf-to-pdf-from-file.cs
using IronPdf;
// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render from RTF file
PdfDocument pdf = renderer.RenderRtfFileAsPdf("sample.rtf");
// Save the PDF
pdf.SaveAs("pdfFromRtfFile.pdf");
Imports IronPdf
' Instantiate Renderer
Private renderer As New ChromePdfRenderer()
' Render from RTF file
Private pdf As PdfDocument = renderer.RenderRtfFileAsPdf("sample.rtf")
' Save the PDF
pdf.SaveAs("pdfFromRtfFile.pdf")
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
MDからPDFに変換
MDをPDFに変換するには、MDファイルを入力としてRenderMarkdownFileAsPdfメソッドを呼び出すことができます。
:path=/static-assets/pdf/content-code-examples/how-to/md-to-pdf-from-file.cs
using IronPdf;
// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render from markdown file
PdfDocument pdf = renderer.RenderMarkdownFileAsPdf("sample.md");
// Save the PDF
pdf.SaveAs("pdfFromMarkdownFile.pdf");
Imports IronPdf
' Instantiate Renderer
Private renderer As New ChromePdfRenderer()
' Render from markdown file
Private pdf As PdfDocument = renderer.RenderMarkdownFileAsPdf("sample.md")
' Save the PDF
pdf.SaveAs("pdfFromMarkdownFile.pdf")
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
XMLからPDFに変換
XMLからPDFへの変換は非常に難しいことがありますが、IronPDFは依然として挑戦に応じ、数ステップでXMLをPDFに変換するのを助けます。 XLSTテンプレートから始め、XLST変換を通じてHTML経由でXMLをPDFに変換します。 開始するのに役立つコードスニペットの短縮版を以下に示します。
// XSLT template that defines the transformation from XML to HTML
string xslt = @"<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:template match='/'>
<html>
<style>
td{
text-align: center;
padding: 20px;
border: 1px solid #CDE7F0;
}
th{
color: white;
padding: 20px;
}
</style>
<body style='font-family: Arial, Helvetica Neue, Helvetica, sans-serif;'>
<table style='border-collapse: collapse;'>
<thead>
<tr>
<th colspan='3'>
<img style='margin: auto;' src='https://ironsoftware.com/img/svgs/ironsoftware-logo-black.svg'/>
</th>
</tr>
</thead>
<tbody>
<tr bgcolor='#9acd32'>
<th bgcolor='#32ab90'>Title</th>
<th bgcolor='#f49400'>Feature</th>
<th bgcolor='#2a95d5'>Compatible</th>
</tr>
<xsl:for-each select='catalog/cd'>
<tr>
<td style='font-weight: bold;'><xsl:value-of select='title'/></td>
<td style='background-color: #eff8fb; color: #2a95d5; font-weight: bold;'><xsl:value-of select='feature'/></td>
<td><xsl:value-of select='compatible'/></td>
</tr>
</xsl:for-each>
</tbody>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
";
// XML data to transform
string xml = @"<?xml version='1.0' encoding='UTF-8'?>
<catalog>
<cd>
<title>IronPDF</title>
<feature>Generate, format and manipulate PDFs</feature>
<compatible>Microsoft Windows, Linux (Debian, CentOS, Ubuntu), MacOS, Docker (Windows, Linux, Azure), Azure (VPS, Webapps, Websites, Functions), AWS</compatible>
</cd>
<cd>
<title>IronOCR</title>
<feature>OCR engine, input, result</feature>
<compatible>Microsoft Windows, Linux, MacOS, Docker, Azure, AWS</compatible>
</cd>
<cd>
<title>IronBarcode</title>
<feature>Format, read and write Barcode</feature>
<compatible>Microsoft Windows, Linux, MacOS, Docker, Azure, AWS</compatible>
</cd>
</catalog>
";
// Create an instance of XslCompiledTransform
XslCompiledTransform transform = new XslCompiledTransform();
// Load the XSLT from a string
using (XmlReader reader = XmlReader.Create(new StringReader(xslt)))
{
transform.Load(reader);
}
// Transform the XML to HTML
StringWriter results = new StringWriter();
using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
transform.Transform(reader, null, results);
}
// Create a renderer for converting HTML to PDF
IronPdf.ChromePdfRenderer renderer = new IronPdf.ChromePdfRenderer();
// Options, headers, and footers may be set here if needed
// Render our XML as a PDF via XSLT transformation
renderer.RenderHtmlAsPdf(results.ToString()).SaveAs("Final.pdf");
// XSLT template that defines the transformation from XML to HTML
string xslt = @"<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:template match='/'>
<html>
<style>
td{
text-align: center;
padding: 20px;
border: 1px solid #CDE7F0;
}
th{
color: white;
padding: 20px;
}
</style>
<body style='font-family: Arial, Helvetica Neue, Helvetica, sans-serif;'>
<table style='border-collapse: collapse;'>
<thead>
<tr>
<th colspan='3'>
<img style='margin: auto;' src='https://ironsoftware.com/img/svgs/ironsoftware-logo-black.svg'/>
</th>
</tr>
</thead>
<tbody>
<tr bgcolor='#9acd32'>
<th bgcolor='#32ab90'>Title</th>
<th bgcolor='#f49400'>Feature</th>
<th bgcolor='#2a95d5'>Compatible</th>
</tr>
<xsl:for-each select='catalog/cd'>
<tr>
<td style='font-weight: bold;'><xsl:value-of select='title'/></td>
<td style='background-color: #eff8fb; color: #2a95d5; font-weight: bold;'><xsl:value-of select='feature'/></td>
<td><xsl:value-of select='compatible'/></td>
</tr>
</xsl:for-each>
</tbody>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
";
// XML data to transform
string xml = @"<?xml version='1.0' encoding='UTF-8'?>
<catalog>
<cd>
<title>IronPDF</title>
<feature>Generate, format and manipulate PDFs</feature>
<compatible>Microsoft Windows, Linux (Debian, CentOS, Ubuntu), MacOS, Docker (Windows, Linux, Azure), Azure (VPS, Webapps, Websites, Functions), AWS</compatible>
</cd>
<cd>
<title>IronOCR</title>
<feature>OCR engine, input, result</feature>
<compatible>Microsoft Windows, Linux, MacOS, Docker, Azure, AWS</compatible>
</cd>
<cd>
<title>IronBarcode</title>
<feature>Format, read and write Barcode</feature>
<compatible>Microsoft Windows, Linux, MacOS, Docker, Azure, AWS</compatible>
</cd>
</catalog>
";
// Create an instance of XslCompiledTransform
XslCompiledTransform transform = new XslCompiledTransform();
// Load the XSLT from a string
using (XmlReader reader = XmlReader.Create(new StringReader(xslt)))
{
transform.Load(reader);
}
// Transform the XML to HTML
StringWriter results = new StringWriter();
using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
transform.Transform(reader, null, results);
}
// Create a renderer for converting HTML to PDF
IronPdf.ChromePdfRenderer renderer = new IronPdf.ChromePdfRenderer();
// Options, headers, and footers may be set here if needed
// Render our XML as a PDF via XSLT transformation
renderer.RenderHtmlAsPdf(results.ToString()).SaveAs("Final.pdf");
' XSLT template that defines the transformation from XML to HTML
Dim xslt As String = "<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:template match='/'>
<html>
<style>
td{
text-align: center;
padding: 20px;
border: 1px solid #CDE7F0;
}
th{
color: white;
padding: 20px;
}
</style>
<body style='font-family: Arial, Helvetica Neue, Helvetica, sans-serif;'>
<table style='border-collapse: collapse;'>
<thead>
<tr>
<th colspan='3'>
<img style='margin: auto;' src='https://ironsoftware.com/img/svgs/ironsoftware-logo-black.svg'/>
</th>
</tr>
</thead>
<tbody>
<tr bgcolor='#9acd32'>
<th bgcolor='#32ab90'>Title</th>
<th bgcolor='#f49400'>Feature</th>
<th bgcolor='#2a95d5'>Compatible</th>
</tr>
<xsl:for-each select='catalog/cd'>
<tr>
<td style='font-weight: bold;'><xsl:value-of select='title'/></td>
<td style='background-color: #eff8fb; color: #2a95d5; font-weight: bold;'><xsl:value-of select='feature'/></td>
<td><xsl:value-of select='compatible'/></td>
</tr>
</xsl:for-each>
</tbody>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
"
' XML data to transform
Dim xml As String = "<?xml version='1.0' encoding='UTF-8'?>
<catalog>
<cd>
<title>IronPDF</title>
<feature>Generate, format and manipulate PDFs</feature>
<compatible>Microsoft Windows, Linux (Debian, CentOS, Ubuntu), MacOS, Docker (Windows, Linux, Azure), Azure (VPS, Webapps, Websites, Functions), AWS</compatible>
</cd>
<cd>
<title>IronOCR</title>
<feature>OCR engine, input, result</feature>
<compatible>Microsoft Windows, Linux, MacOS, Docker, Azure, AWS</compatible>
</cd>
<cd>
<title>IronBarcode</title>
<feature>Format, read and write Barcode</feature>
<compatible>Microsoft Windows, Linux, MacOS, Docker, Azure, AWS</compatible>
</cd>
</catalog>
"
' Create an instance of XslCompiledTransform
Dim transform As New XslCompiledTransform()
' Load the XSLT from a string
Using reader As XmlReader = XmlReader.Create(New StringReader(xslt))
transform.Load(reader)
End Using
' Transform the XML to HTML
Dim results As New StringWriter()
Using reader As XmlReader = XmlReader.Create(New StringReader(xml))
transform.Transform(reader, Nothing, results)
End Using
' Create a renderer for converting HTML to PDF
Dim renderer As New IronPdf.ChromePdfRenderer()
' Options, headers, and footers may be set here if needed
' Render our XML as a PDF via XSLT transformation
renderer.RenderHtmlAsPdf(results.ToString()).SaveAs("Final.pdf")
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
PDFからHTMLに
さまざまな形式をPDFに変換することに加えて、IronPDFはPDFをHTMLに変換する逆の操作もサポートしています。 機能を示す簡単なコードスニペットを以下に示します。
:path=/static-assets/pdf/content-code-examples/how-to/pdf-to-html.cs
using IronPdf;
using System;
PdfDocument pdf = PdfDocument.FromFile("sample.pdf");
// Convert PDF to HTML string
string html = pdf.ToHtmlString();
Console.WriteLine(html);
// Convert PDF to HTML file
pdf.SaveAsHtml("myHtml.html");
IRON VB CONVERTER ERROR developers@ironsoftware.com
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
動的WebページからPDFに
動的なWebページを元のレイアウトとフォーマットを保持しながらPDFに変換する必要がありますか? IronPDFを使えば、さまざまな人気のある動的WebページフレームワークをすばやくPDFに変換できます。
ASPXページからPDFに変換
Active Server PagesでASPXページをPDFとして変換する簡潔なコードスニペットを以下に示します。
:path=/static-assets/pdf/content-code-examples/how-to/aspx-to-pdf-2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IronPdf;
namespace AspxToPdfTutorial
{
public partial class Invoice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
IronPdf.AspxToPdf.RenderThisPageAsPdf(IronPdf.AspxToPdf.FileBehavior.InBrowser);
}
}
}
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports IronPdf
Namespace AspxToPdfTutorial
Partial Public Class Invoice
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
IronPdf.AspxToPdf.RenderThisPageAsPdf(IronPdf.AspxToPdf.FileBehavior.InBrowser)
End Sub
End Class
End Namespace
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
XAMLからPDFに (MAUI)
クロスプラットフォームアプリケーションを構築する開発者にとって、.NET MAUIはフレームワークの中で人気のある選択肢です。 IronPDFはXAMLをPDFに数ステップで完全にサポートしています。
:path=/static-assets/pdf/content-code-examples/how-to/xaml-to-pdf-maui-mainpage-xaml-cs.cs
using IronPdf.Extensions.Maui;
namespace mauiSample;
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void PrintToPdf(object sender, EventArgs e)
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Apply HTML header
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
HtmlFragment = "<h1>Header</h1>",
};
// Render PDF from Maui Page
PdfDocument pdf = renderer.RenderContentPageToPdf<MainPage, App>().Result;
pdf.SaveAs(@"C:\Users\lyty1\Downloads\contentPageToPdf.pdf");
}
}
Imports IronPdf.Extensions.Maui
Namespace mauiSample
Partial Public Class MainPage
Inherits ContentPage
Public Sub New()
InitializeComponent()
End Sub
Private Sub PrintToPdf(ByVal sender As Object, ByVal e As EventArgs)
Dim renderer As New ChromePdfRenderer()
' Apply HTML header
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter() With {.HtmlFragment = "<h1>Header</h1>"}
' Render PDF from Maui Page
Dim pdf As PdfDocument = renderer.RenderContentPageToPdf(Of MainPage, App)().Result
pdf.SaveAs("C:\Users\lyty1\Downloads\contentPageToPdf.pdf")
End Sub
End Class
End Namespace
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
PDFレポートの生成
PDFレポートの生成において、正確な寸法と形式が重要です。 そのため、IronPDFを使用すると数ステップでシームレスにPDFを生成できます。
:path=/static-assets/pdf/content-code-examples/how-to/csharp-pdf-reports-render-html-file.cs
using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderHtmlFileAsPdf("report.html").SaveAs("report.pdf");
Imports IronPdf
Private renderer As New ChromePdfRenderer()
renderer.RenderHtmlFileAsPdf("report.html").SaveAs("report.pdf")
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
BlazorサーバーでのPDF作成
IronPDFは.NET 6をサポートしており、Blazorのようなプロジェクトタイプを含んでいるため、BlazorサーバーでPDFを作成する方法を簡単なコードスニペットで示します。
@code {
// Model to bind user input
private InputHTMLModel _InputMsgModel = new InputHTMLModel();
private async Task SubmitHTML()
{
// Set your IronPDF license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
// Create a renderer to convert HTML to PDF
var render = new IronPdf.ChromePdfRenderer();
// Render the HTML input into a PDF document
var doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML);
var fileName = "iron.pdf";
// Create a stream reference for the PDF content
using var streamRef = new DotNetStreamReference(stream: doc.Stream);
// Invoke JavaScript function to download the PDF in the browser
await JS.InvokeVoidAsync("SubmitHTML", fileName, streamRef);
}
public class InputHTMLModel
{
public string HTML { get; set; } = "My new message";
}
}
@code {
// Model to bind user input
private InputHTMLModel _InputMsgModel = new InputHTMLModel();
private async Task SubmitHTML()
{
// Set your IronPDF license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
// Create a renderer to convert HTML to PDF
var render = new IronPdf.ChromePdfRenderer();
// Render the HTML input into a PDF document
var doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML);
var fileName = "iron.pdf";
// Create a stream reference for the PDF content
using var streamRef = new DotNetStreamReference(stream: doc.Stream);
// Invoke JavaScript function to download the PDF in the browser
await JS.InvokeVoidAsync("SubmitHTML", fileName, streamRef);
}
public class InputHTMLModel
{
public string HTML { get; set; } = "My new message";
}
}
code
If True Then
' Model to bind user input
private InputHTMLModel _InputMsgModel = New InputHTMLModel()
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
' private async Task SubmitHTML()
' {
' ' Set your IronPDF license key
' IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
'
' ' Create a renderer to convert HTML to PDF
' var render = New IronPdf.ChromePdfRenderer();
'
' ' Render the HTML input into a PDF document
' var doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML);
'
' var fileName = "iron.pdf";
'
' ' Create a stream reference for the PDF content
' var streamRef = New DotNetStreamReference(stream: doc.Stream);
'
' ' Invoke JavaScript function to download the PDF in the browser
' await JS.InvokeVoidAsync("SubmitHTML", fileName, streamRef);
' }
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
' public class InputHTMLModel
' {
' public string HTML
' {
' get;
' set;
' } = "My new message";
' }
End If
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
RazorからPDF(Blazorサーバー)
BlazorサーバーでPDFを作成することに加えて、IronPDFはBlazorページ内のRazorコンポーネントからPDFドキュメントを生成することもサポートしています。 PDFファイルやページの作成をはるかに合理化します。
[Parameter]
public IEnumerable<PersonInfo> persons { get; set; }
public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>();
protected override async Task OnInitializedAsync()
{
persons = new List<PersonInfo>
{
new PersonInfo { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new PersonInfo { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new PersonInfo { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
}
private async void PrintToPdf()
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Apply text footer
renderer.RenderingOptions.TextFooter = new TextHeaderFooter()
{
LeftText = "{date} - {time}",
DrawDividerLine = true,
RightText = "Page {page} of {total-pages}",
Font = IronSoftware.Drawing.FontTypes.Arial,
FontSize = 11
};
Parameters.Add("persons", persons);
// Render razor component to PDF
PdfDocument pdf = renderer.RenderRazorComponentToPdf<Person>(Parameters);
File.WriteAllBytes("razorComponentToPdf.pdf", pdf.BinaryData);
}
[Parameter]
public IEnumerable<PersonInfo> persons { get; set; }
public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>();
protected override async Task OnInitializedAsync()
{
persons = new List<PersonInfo>
{
new PersonInfo { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new PersonInfo { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new PersonInfo { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
}
private async void PrintToPdf()
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Apply text footer
renderer.RenderingOptions.TextFooter = new TextHeaderFooter()
{
LeftText = "{date} - {time}",
DrawDividerLine = true,
RightText = "Page {page} of {total-pages}",
Font = IronSoftware.Drawing.FontTypes.Arial,
FontSize = 11
};
Parameters.Add("persons", persons);
// Render razor component to PDF
PdfDocument pdf = renderer.RenderRazorComponentToPdf<Person>(Parameters);
File.WriteAllBytes("razorComponentToPdf.pdf", pdf.BinaryData);
}
<Parameter>
Public Property persons() As IEnumerable(Of PersonInfo)
Public Property Parameters() As New Dictionary(Of String, Object)()
Protected Overrides Async Function OnInitializedAsync() As Task
persons = New List(Of PersonInfo) From {
New PersonInfo With {
.Name = "Alice",
.Title = "Mrs.",
.Description = "Software Engineer"
},
New PersonInfo With {
.Name = "Bob",
.Title = "Mr.",
.Description = "Software Engineer"
},
New PersonInfo With {
.Name = "Charlie",
.Title = "Mr.",
.Description = "Software Engineer"
}
}
End Function
Private Async Sub PrintToPdf()
Dim renderer As New ChromePdfRenderer()
' Apply text footer
renderer.RenderingOptions.TextFooter = New TextHeaderFooter() With {
.LeftText = "{date} - {time}",
.DrawDividerLine = True,
.RightText = "Page {page} of {total-pages}",
.Font = IronSoftware.Drawing.FontTypes.Arial,
.FontSize = 11
}
Parameters.Add("persons", persons)
' Render razor component to PDF
Dim pdf As PdfDocument = renderer.RenderRazorComponentToPdf(Of Person)(Parameters)
File.WriteAllBytes("razorComponentToPdf.pdf", pdf.BinaryData)
End Sub
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
CSHTMLからPDFに
CSHTML(Razor)からPDFへの変換により、Webアプリケーションから直接プロフェッショナルで印刷準備が整ったドキュメントを生成できます。 これは請求書、レポート、契約書、または動的なコンテンツに役立ちます。 IronPDFはRazor Pages、MVC Core、MVC Framework、およびヘッドレスレンダリングをサポートしており、わずか数行のコードで.NETアプリケーションにPDF生成をシームレスに統合できます。
CSHTMLからPDFに (Razor Pages)
using IronPdf.Razor.Pages;
public IActionResult OnPostAsync()
{
persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
ViewData["personList"] = persons;
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render Razor Page to PDF document
PdfDocument pdf = renderer.RenderRazorToPdf(this);
Response.Headers.Add("Content-Disposition", "inline");
return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf");
}
using IronPdf.Razor.Pages;
public IActionResult OnPostAsync()
{
persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
ViewData["personList"] = persons;
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render Razor Page to PDF document
PdfDocument pdf = renderer.RenderRazorToPdf(this);
Response.Headers.Add("Content-Disposition", "inline");
return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf");
}
Imports IronPdf.Razor.Pages
Public Function OnPostAsync() As IActionResult
persons = New List(Of Person) From {
New Person With {
.Name = "Alice",
.Title = "Mrs.",
.Description = "Software Engineer"
},
New Person With {
.Name = "Bob",
.Title = "Mr.",
.Description = "Software Engineer"
},
New Person With {
.Name = "Charlie",
.Title = "Mr.",
.Description = "Software Engineer"
}
}
ViewData("personList") = persons
Dim renderer As New ChromePdfRenderer()
' Render Razor Page to PDF document
Dim pdf As PdfDocument = renderer.RenderRazorToPdf(Me)
Response.Headers.Add("Content-Disposition", "inline")
Return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf")
End Function
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
CSHTMLからPDFに (MVC Core)
public async Task<IActionResult> Persons()
{
var persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
if (_httpContextAccessor.HttpContext.Request.Method == HttpMethod.Post.Method)
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render View to PDF document
PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons);
Response.Headers.Add("Content-Disposition", "inline");
// Output PDF document
return File(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf");
}
return View(persons);
}
public async Task<IActionResult> Persons()
{
var persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
if (_httpContextAccessor.HttpContext.Request.Method == HttpMethod.Post.Method)
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render View to PDF document
PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons);
Response.Headers.Add("Content-Disposition", "inline");
// Output PDF document
return File(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf");
}
return View(persons);
}
Public Async Function Persons() As Task(Of IActionResult)
'INSTANT VB NOTE: The local variable persons was renamed since Visual Basic will not allow local variables with the same name as their enclosing function or property:
Dim persons_Conflict = New List(Of Person) From {
New Person With {
.Name = "Alice",
.Title = "Mrs.",
.Description = "Software Engineer"
},
New Person With {
.Name = "Bob",
.Title = "Mr.",
.Description = "Software Engineer"
},
New Person With {
.Name = "Charlie",
.Title = "Mr.",
.Description = "Software Engineer"
}
}
If _httpContextAccessor.HttpContext.Request.Method = HttpMethod.Post.Method Then
Dim renderer As New ChromePdfRenderer()
' Render View to PDF document
Dim pdf As PdfDocument = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons_Conflict)
Response.Headers.Add("Content-Disposition", "inline")
' Output PDF document
Return File(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf")
End If
Return View(persons_Conflict)
End Function
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
CSHTMLからPDFに (MVC Framework)
public ActionResult Persons()
{
var persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
if (HttpContext.Request.HttpMethod == "POST")
{
// Provide the path to your view file
var viewPath = "~/Views/Home/Persons.cshtml";
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render Razor view to PDF document
PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);
Response.Headers.Add("Content-Disposition", "inline");
// View the PDF
return File(pdf.BinaryData, "application/pdf");
}
return View(persons);
}
public ActionResult Persons()
{
var persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
if (HttpContext.Request.HttpMethod == "POST")
{
// Provide the path to your view file
var viewPath = "~/Views/Home/Persons.cshtml";
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render Razor view to PDF document
PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);
Response.Headers.Add("Content-Disposition", "inline");
// View the PDF
return File(pdf.BinaryData, "application/pdf");
}
return View(persons);
}
Public Function Persons() As ActionResult
'INSTANT VB NOTE: The local variable persons was renamed since Visual Basic will not allow local variables with the same name as their enclosing function or property:
Dim persons_Conflict = New List(Of Person) From {
New Person With {
.Name = "Alice",
.Title = "Mrs.",
.Description = "Software Engineer"
},
New Person With {
.Name = "Bob",
.Title = "Mr.",
.Description = "Software Engineer"
},
New Person With {
.Name = "Charlie",
.Title = "Mr.",
.Description = "Software Engineer"
}
}
If HttpContext.Request.HttpMethod = "POST" Then
' Provide the path to your view file
Dim viewPath = "~/Views/Home/Persons.cshtml"
Dim renderer As New ChromePdfRenderer()
' Render Razor view to PDF document
Dim pdf As PdfDocument = renderer.RenderView(Me.HttpContext, viewPath, persons_Conflict)
Response.Headers.Add("Content-Disposition", "inline")
' View the PDF
Return File(pdf.BinaryData, "application/pdf")
End If
Return View(persons_Conflict)
End Function
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
CSHTMLからPDFに (Headlessly)
app.MapGet("/PrintPdf", async () =>
{
// Set your IronPDF license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
// Enable detailed logging for troubleshooting
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;
// Render the Razor view to an HTML string
string html = await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml");
// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render the HTML string as a PDF document
PdfDocument pdf = renderer.RenderHtmlAsPdf(html, "./wwwroot");
// Return the PDF file as a response
return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf");
});
app.MapGet("/PrintPdf", async () =>
{
// Set your IronPDF license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
// Enable detailed logging for troubleshooting
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;
// Render the Razor view to an HTML string
string html = await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml");
// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render the HTML string as a PDF document
PdfDocument pdf = renderer.RenderHtmlAsPdf(html, "./wwwroot");
// Return the PDF file as a response
return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf");
});
app.MapGet("/PrintPdf", Async Function()
' Set your IronPDF license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
' Enable detailed logging for troubleshooting
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All
' Render the Razor view to an HTML string
Dim html As String = Await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml")
' Create a new instance of ChromePdfRenderer
Dim renderer As New ChromePdfRenderer()
' Render the HTML string as a PDF document
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html, "./wwwroot")
' Return the PDF file as a response
Return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf")
End Function)
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
ウェブアクセシビリティ
TLSウェブサイト&システムログイン
IronPDFは認証が必要なWebページを変換するための簡単なソリューションを提供します。 レンダリングオプションを使用して、ChromeHttpLoginCredntialsプロパティを使用してユーザー名とパスワードをバイパスできます。
:path=/static-assets/pdf/content-code-examples/how-to/logins-username-password.cs
using IronPdf;
using System;
ChromePdfRenderer renderer = new ChromePdfRenderer
{
// setting login credentials to bypass basic authentication
LoginCredentials = new ChromeHttpLoginCredentials()
{
NetworkUsername = "testUser",
NetworkPassword = "testPassword"
}
};
var uri = new Uri("http://localhost:51169/Invoice");
// Render web URL to PDF
PdfDocument pdf = renderer.RenderUrlAsPdf(uri);
// Export PDF
pdf.SaveAs("UrlToPdfExample.Pdf");
Imports IronPdf
Imports System
Private renderer As New ChromePdfRenderer With {
.LoginCredentials = New ChromeHttpLoginCredentials() With {
.NetworkUsername = "testUser",
.NetworkPassword = "testPassword"
}
}
Private uri = New Uri("http://localhost:51169/Invoice")
' Render web URL to PDF
Private pdf As PdfDocument = renderer.RenderUrlAsPdf(uri)
' Export PDF
pdf.SaveAs("UrlToPdfExample.Pdf")
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
クッキー
追加のログインリクエストにクッキーを適用して、セッションが保存されるようにします! これにより、ロックされたドメイン内での追加リソースのレンダリングが簡単になり、すべてIronPDF内で実行できます。
:path=/static-assets/pdf/content-code-examples/how-to/cookies-apply-cookies.cs
using IronPdf;
// Instantiate ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.RequestContext = IronPdf.Rendering.RequestContexts.Global;
ChromeHttpLoginCredentials credentials = new ChromeHttpLoginCredentials() {
NetworkUsername = "testUser",
NetworkPassword = "testPassword"
};
string uri = "http://localhost:51169/Invoice";
// Apply cookies
renderer.ApplyCookies(uri, credentials);
Imports IronPdf
' Instantiate ChromePdfRenderer
Private renderer As New ChromePdfRenderer()
renderer.RenderingOptions.RequestContext = IronPdf.Rendering.RequestContexts.Global
Dim credentials As New ChromeHttpLoginCredentials() With {
.NetworkUsername = "testUser",
.NetworkPassword = "testPassword"
}
Dim uri As String = "http://localhost:51169/Invoice"
' Apply cookies
renderer.ApplyCookies(uri, credentials)
このコードスニペットの詳細な説明と追加機能を探るには、総合적なハウツーガイドを参照してください。
HTTPリクエストヘッダー
クッキーに加えて、IronPDFはユーザーが承認トークンやその他の関連フィールドを使用してHTTPリクエストヘッダーをカスタマイズすることを許可します。
:path=/static-assets/pdf/content-code-examples/how-to/http-request-header.cs
using IronPdf;
using System.Collections.Generic;
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.HttpRequestHeaders = new Dictionary<string, string>
{
{ "Authorization", "Bearer test-token-123" }
};
// Render PDF from authenticated page
var pdf = renderer.RenderUrlAsPdf("https://httpbin.org/bearer");
pdf.SaveAs("output.pdf");
Imports IronPdf
Imports System.Collections.Generic
Private renderer = New ChromePdfRenderer()
renderer.RenderingOptions.HttpRequestHeaders = New Dictionary(Of String, String) From {
{"Authorization", "Bearer test-token-123"}
}
' Render PDF from authenticated page
Dim pdf = renderer.RenderUrlAsPdf("https://httpbin.org/bearer")
pdf.SaveAs("output.pdf")
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
PDF変換のカスタマイズ
レンダリングオプション
IronPDFを使用すると、生成されたPDFの外観と形式をカスタマイズできます。 さまざまな入力をPDFに変換するために使用されるChromePdfRenderクラスには、RenderingOptionsプロパティも含まれており、出力の見え方をユーザーが制御できます。
:path=/static-assets/pdf/content-code-examples/how-to/rendering-options-render.cs
using IronPdf;
// Instantiate a ChromePdfRenderer object, which uses a headless version of the Chrome browser
// to render HTML/CSS as a PDF document.
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Configure rendering options
// Enable printing of HTML backgrounds to ensure all styles are visible.
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
// Set HTML header content using HtmlHeaderFooter.
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
// HTML fragment to add a header at the top of every page in the PDF.
HtmlFragment = "<h1>Header Content</h1>"
};
// Set a custom paper size for the PDF in millimeters (width and height).
renderer.RenderingOptions.SetCustomPaperSizeinMilimeters(150, 150);
// Set the top margin to zero to start the content from the very top of the page.
renderer.RenderingOptions.MarginTop = 0;
// Define a Markdown string that will be rendered as a PDF.
// Markdown text allows basic formatting like bold and italic styles.
string md = "This is some **bold** and *italic* text.";
// Render the Markdown string to a PDF document.
// The library will convert Markdown syntax into equivalent HTML before rendering it as a PDF.
PdfDocument pdf = renderer.RenderMarkdownStringAsPdf(md);
// Save the generated PDF to a file named "renderingOptions.pdf."
pdf.SaveAs("renderingOptions.pdf");
Imports IronPdf
' Instantiate a ChromePdfRenderer object, which uses a headless version of the Chrome browser
' to render HTML/CSS as a PDF document.
Private renderer As New ChromePdfRenderer()
' Configure rendering options
' Enable printing of HTML backgrounds to ensure all styles are visible.
renderer.RenderingOptions.PrintHtmlBackgrounds = True
' Set HTML header content using HtmlHeaderFooter.
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter With {.HtmlFragment = "<h1>Header Content</h1>"}
' Set a custom paper size for the PDF in millimeters (width and height).
renderer.RenderingOptions.SetCustomPaperSizeinMilimeters(150, 150)
' Set the top margin to zero to start the content from the very top of the page.
renderer.RenderingOptions.MarginTop = 0
' Define a Markdown string that will be rendered as a PDF.
' Markdown text allows basic formatting like bold and italic styles.
Dim md As String = "This is some **bold** and *italic* text."
' Render the Markdown string to a PDF document.
' The library will convert Markdown syntax into equivalent HTML before rendering it as a PDF.
Dim pdf As PdfDocument = renderer.RenderMarkdownStringAsPdf(md)
' Save the generated PDF to a file named "renderingOptions.pdf."
pdf.SaveAs("renderingOptions.pdf")
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
カスタムマージンの設定
出力PDFの外観をさらにカスタマイズするには、マージンを調整してレイアウトやスペースを正確に制御できます。
:path=/static-assets/pdf/content-code-examples/how-to/custom-margins-set-margins.cs
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.MarginTop = 40;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;
renderer.RenderingOptions.MarginBottom = 40;
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.MarginTop = 40
renderer.RenderingOptions.MarginLeft = 20
renderer.RenderingOptions.MarginRight = 20
renderer.RenderingOptions.MarginBottom = 40
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
グレースケール
グレースケールのPDFを生成するには、RenderingOptions内のGrayScaleプロパティをtrueに設定します。
:path=/static-assets/pdf/content-code-examples/how-to/color-grayscale-grayscale.cs
using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Set GrayScale to true
renderer.RenderingOptions.GrayScale = true;
PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironsoftware.com/");
pdf.CopyPage(0).SaveAs("test.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
PDFレイアウトの改善
目次の追加
IronPDFを使用して動的な目次を作成し、読者がドキュメントを簡単にナビゲートできるようにします。 IronPDFはh1やh2などのヘッダーへのハイパーリンクを備えた目次を自動的に処理します。 その上に、HTMLとCSSスタイリングを使用して目次のスタイルをカスタマイズすることもできます。
:path=/static-assets/pdf/content-code-examples/how-to/table-of-contents.cs
using IronPdf;
// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Configure render options
renderer.RenderingOptions = new ChromePdfRenderOptions
{
// Enable table of content feature
TableOfContents = TableOfContentsTypes.WithPageNumbers,
};
PdfDocument pdf = renderer.RenderHtmlFileAsPdf("tableOfContent.html");
pdf.SaveAs("tableOfContents.pdf");
Imports IronPdf
' Instantiate Renderer
Private renderer As New ChromePdfRenderer()
' Configure render options
renderer.RenderingOptions = New ChromePdfRenderOptions With {.TableOfContents = TableOfContentsTypes.WithPageNumbers}
Dim pdf As PdfDocument = renderer.RenderHtmlFileAsPdf("tableOfContent.html")
pdf.SaveAs("tableOfContents.pdf")
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
ページブレーク
セクション間にページブレークを追加してコンテンツを明確に分離し、ドキュメントの可読性を向上させます。 IronPDFを使用して、HTML div style= page-break-afterを使用してその効果を達成します。
:path=/static-assets/pdf/content-code-examples/how-to/html-to-pdf-page-breaks-page-break.cs
using IronPdf;
const string html = @"
<table style='border: 1px solid #000000'>
<tr>
<th>Company</th>
<th>Product</th>
</tr>
<tr>
<td>Iron Software</td>
<td>IronPDF</td>
</tr>
<tr>
<td>Iron Software</td>
<td>IronOCR</td>
</tr>
</table>
<div style='page-break-after: always;'> </div>
<img src='https://ironpdf.com/img/products/ironpdf-logo-text-dotnet.svg'>";
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("Page_Break.pdf");
Imports IronPdf
Private Const html As String = "
<table style='border: 1px solid #000000'>
<tr>
<th>Company</th>
<th>Product</th>
</tr>
<tr>
<td>Iron Software</td>
<td>IronPDF</td>
</tr>
<tr>
<td>Iron Software</td>
<td>IronOCR</td>
</tr>
</table>
<div style='page-break-after: always;'> </div>
<img src='https://ironpdf.com/img/products/ironpdf-logo-text-dotnet.svg'>"
Private renderer = New ChromePdfRenderer()
Private pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("Page_Break.pdf")
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
ページに合わせて調整&ズーム
指定された用紙サイズに収まるようにコンテンツの寸法を決定する手助けが必要ですか?IronPDFには、Google Chromeの印刷プレビューがコンテンツをページに合わせてスケールする方法を模倣するUseChromeDefaultがあります。
:path=/static-assets/pdf/content-code-examples/how-to/viewport-zoom-default-chrome.cs
using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Chrome default rendering
renderer.RenderingOptions.PaperFit.UseChromeDefaultRendering();
// Render web URL to PDF
PdfDocument pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");
pdf.SaveAs("chromeDefault.pdf");
Imports IronPdf
Private renderer As New ChromePdfRenderer()
' Chrome default rendering
renderer.RenderingOptions.PaperFit.UseChromeDefaultRendering()
' Render web URL to PDF
Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page")
pdf.SaveAs("chromeDefault.pdf")
このコードスニペットの詳細な説明と追加機能を探るには、総合的なハウツーガイドを参照してください。
結論
上記の例は、さまざまな形式をPDFに変換する際にIronPDFを使用してアンロックできる印象的な機能と注目の特長を示しています。
機能要望をリクエストしたい場合、またはIronPDFまたはライセンスについての一般的な質問がある場合は、サポートチームにお問い合わせください。 喜んでお手伝いいたします。
よくある質問
.NET CoreでHTMLをPDFに変換するにはどうすればよいですか?
.NET CoreでHTMLをPDFに変換するには、IronPDFライブラリを使用します。まず、NuGetを介してパッケージをインストールします。次に、ChromePdfRendererのインスタンスを作成し、RenderHtmlAsPdfメソッドを利用してHTML文字列をPDF形式に変換します。
ライブURLをPDFドキュメントに変換する方法は?
IronPDFを使用して、ライブURLをPDFドキュメントに変換できます。ライブラリをNuGetからインストールし、ChromePdfRendererインスタンスを作成し、変換したいウェブページURLでRenderUrlAsPdfメソッドを呼び出します。
RazorビューをPDFに変換する手順は?
RazorビューをPDFに変換するには、ビューをHTML文字列にレンダリングし、それをIronPDFのRenderHtmlAsPdfメソッドに渡します。これにより、MVCビューから完全なデータバインディングを持つ動的なPDFを作成できます。
既存のPDFファイルは変更可能ですか?
はい、既存のPDFファイルはIronPDFを使用して変更可能です。PdfDocument.FromFileを使用してPDFをロードし、マージ、ヘッダー/フッターの追加、セキュリティ設定の変更などの修正を適用します。
PDFをレンダリングするためのオプションは何ですか?
IronPDFはChromePdfRenderOptionsを通じてさまざまなレンダリングオプションを提供します。用紙サイズ、向き、余白などをカスタマイズして、特定のレイアウトとスタイル要件を満たすPDFを確保できます。
PDFをDocker環境でデプロイするにはどうすればよいですか?
Dockerfile内でLinuxの依存関係を構成することで、Docker環境でPDFをデプロイします。IronPDFのIronPdf.Installation.LinuxAndDockerDependenciesAutoConfigを使用して、コンテナアプリケーションで自動的に依存関係を処理します。
PDFファイルにデジタル署名を追加することは可能ですか?
はい、PdfSignatureクラスを使用してPDFファイルにデジタル署名を追加できます。Signメソッドと証明書ファイルを利用して、ドキュメントの信頼性と整合性を確保します。
IronPDFがPDFに提供するセキュリティ機能は何ですか?
IronPDFはパスワード保護、暗号化、アクセス制御を含む堅牢なセキュリティ機能を提供します。 SecuritySettingsプロパティを介して、表示、印刷、編集の権限を管理することができます。
PDFドキュメントからテキストと画像を抽出する方法は?
IronPDFのExtractAllTextとExtractAllImagesメソッドを使用して、PDFドキュメントからテキストと画像を抽出できます。これにより、ドキュメント全体または特定のページからデータを処理することができます。
PDFファイルに透かしを適用するにはどうすればよいですか?
IronPDFのWatermarkプロパティを使用し、HtmlStampオブジェクトと共にPDFファイルに透かしを適用できます。 より高度なニーズに対してはHtmlStamperクラスを使用し、カスタマイズ可能なスタイルを持つHTMLベースのスタンプをサポートします。
IronPDF は .NET 10 と互換性がありますか? また、.NET 10 プロジェクトではどのように使用すればよいですか?
はい。IronPDF は、クロスプラットフォームの最新 .NET バージョンサポートの一環として、.NET 10 を完全にサポートしています。.NET 10 プロジェクトで使用するには、 IronPdf NuGet パッケージをインストールし、プロジェクトファイルでnet10.0をターゲットとして参照し、 ChromePdfRendererなどのクラスやRenderHtmlAsPdfなどのメソッドを、以前の .NET バージョンと同様に使用します。PDF のレンダリングや操作時に、.NET 10 特有のパフォーマンス、メモリ使用量、ランタイム拡張機能の向上を活用できます。

